package com.ankicoo.auth.controller;

import com.ankicoo.auth.service.UserService;
import com.ankicoo.common.response.ResponseBody;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Optional;

/**
 * Description: 登录接口
 *
 * @author : QCYANG
 * data : 2021/1/10 15:56
 */
@RestController
@RequestMapping("/auth")
public class LoginController {
    @Autowired
    private UserService userService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @PostMapping("/login")
    public ResponseBody<String> login(@RequestBody Map<String, String> map) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(map.get("username"),
                map.get("password"));
        try {
            subject.login(usernamePasswordToken);
            logger.info("身份验证成功");
            return ResponseBody.createBySuccess("登录成功", "normalLogin");
        } catch (AuthenticationException e) {
            logger.info("身份验证失败");
            return ResponseBody.createByErrorMessageData("登陆失败", "loginFail");
        }
    }

    @GetMapping("/logout")
    public ResponseBody<String> logout() {
        Subject subject = SecurityUtils.getSubject();
        if (Optional.ofNullable(subject).isPresent()) {
            subject.logout();
        }
        return ResponseBody.createBySuccessMessage("成功退出系统");
    }
}
